package com.jzg.jcptadmin.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.base.BaseObject;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.vo.TouXiangInfo;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.UserInfoPresenter;
import com.jzg.jcptadmin.view.ActionSheet;
import com.jzg.jcptadmin.viewinterface.UserInfoInterface;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserInfoActivity extends BaseActivity  implements UserInfoInterface, ActionSheet.OnActionSheetSelected,
        DialogInterface.OnCancelListener{
    private static final int MY_PERMISSIONS_1 = 10;
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.nicheng)
    TextView nicheng;
    @Bind(R.id.diqu)
    TextView diqu;
    @Bind(R.id.changepd)
    TextView changepd;
    @Bind(R.id.title_content)
    TextView titleContent;
    private User user;
    public String savePath;//拍照的临时文件
    private UserInfoPresenter presenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        ButterKnife.bind(this);
        user = appContext.getUser();
        titleContent.setText("账户详情");
        presenter = new UserInfoPresenter(DataManager.getInstance());
        presenter.attachView(this);
        ImageLoader.getInstance().displayImage(user.getUserPic(), img, appContext.options);
        nicheng.setText(user.getNickName());
        if(user.getProvinceName().equals(user.getCityName())){
            diqu.setText(user.getProvinceName());
        }else{
            diqu.setText(user.getProvinceName()+" "+user.getCityName());
        }

    }

    @OnClick({R.id.img_layout, R.id.nicheng_layout, R.id.changepd})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_layout:
                ActionSheet.showSheet(this,this,this, "从相册选取", "拍照", "取消",
                        R.id.photo, R.id.take, true);
//                Intent intent = new Intent(this,TouXiangActivity.class);

                break;
            case R.id.nicheng_layout:
                ActivityHelp.startCheckInputActivity(this, Constant.NICHENG, "昵称", "请填写昵称(最长6位)",
                        -1, 6, nicheng.getText().toString());
                break;
            case R.id.changepd:
                ActivityHelp.startActivity(this, ChangePdActivity.class);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            case Constant.PHOTO_GRAPH:
                if (RESULT_CANCELED != resultCode) {
                    Intent intent = new Intent(this,TouXiangActivity.class);
                    intent.putExtra("path",savePath);
                    startActivityForResult(intent, Constant.TOUXIANG);
                }
                break;
            case Constant.PHOTO_ZOOM:
                // 从相册传递
                if (data != null) {
                    Uri uri = data.getData();
                    Intent intent = new Intent(this,TouXiangActivity.class);
                    savePath= uri2Path(uri);
                    intent.putExtra("path",savePath);
                    startActivityForResult(intent, Constant.TOUXIANG);
                }

                break;
            case Constant.TOUXIANG:
                //裁切图片后上传图片
                if (data != null) {
                    showDialog();
                    presenter.updateImage(user.getUserId() + "", savePath);
                }

                break;
            case Constant.NICHENG:
                //输入昵称后保存昵称
                if (data != null) {
                    String nickname = data.getStringExtra(Constant.ACTIVITY_INPUT);
                    if(nickname.length()>1){
                        showDialog();
                        nicheng.setText(nickname);
                        presenter.updateNickName();
                    }else{
                        Toast.makeText(UserInfoActivity.this, "昵称长度必须大于2", Toast.LENGTH_SHORT).show();
                    }

                }
                break;

            default:
                break;
        }
    }


    /**
     * 根据Uri获取图片绝对路径 uri2Path
     *
     * @param @param  uri
     * @param @return
     * @return String
     * @throws
     * @Title: uri2Path
     * @Description: TODO
     */
    public String uri2Path(Uri uri) {
        int actual_image_column_index;
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = appContext.getContentResolver().query(uri, proj, null, null, null);
        actual_image_column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        img_path = cursor.getString(actual_image_column_index);
        return img_path;
    }
    @Override
    public void onClick(int whichButton) {
        switch (whichButton) {
            // 相册选取
            case R.id.photo:
                String status = Environment.getExternalStorageState();
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                    Intent in = new Intent(Intent.ACTION_PICK, null);
                    in.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            Constant.IMAGE_UNSPECIFIED);
                    startActivityForResult(in, Constant.PHOTO_ZOOM);
                } else {
                    Toast.makeText(this, "没有储存卡", Toast.LENGTH_LONG).show();
                }

                break;
            // 拍照上传
            case R.id.take:

                MPermissions.requestPermissions(UserInfoActivity.this, MY_PERMISSIONS_1,
                        Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            default:
                break;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @PermissionGrant(MY_PERMISSIONS_1)
    public void requestSdcardSuccess() {
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        savePath = Environment.getExternalStorageDirectory() + "/JZGErShouChe/temp.jpg";
        Uri imageUri = Uri.fromFile(new File(savePath));
        // 指定照片保存路径（SD卡），temp.jpg为一个临时文件，每次拍照后这个图片都会被替换
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(cameraIntent, Constant.PHOTO_GRAPH);
    }
    @PermissionDenied(MY_PERMISSIONS_1)
    public void requestSdcardFailed() {
        Toast.makeText(this, "授权被拒!", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onCancel(DialogInterface dialog) {

    }

    @Override
    public Map<String, String> getLoadStatusParams() {
        return null;
    }

    @Override
    public void updateNickName(BaseObject object) {
        dismissDialog();
        user.setNickName(nicheng.getText().toString());
        ACache.get(appContext).put("User", user);
        Toast.makeText(UserInfoActivity.this, object.getMsg(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(String error) {
        super.showError(error);
        dismissDialog();
    }

    @Override
    public void updateImg(TouXiangInfo info) {
        dismissDialog();
        ImageLoader.getInstance().displayImage(info.getPicPath(), img, appContext.options);
        user.setUserPic(info.getPicPath());
        ACache.get(appContext).put("User",user);
    }

    @Override
    public Map<String, String> getNickNameParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("nickName", nicheng.getText().toString());
        params.put("userId", user.getUserId()+"");
        params.put("op", "changeNickName");
        params.put("tokenid", "6");
        Map<String, Object> signMap = new HashMap<>();
        signMap.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMap));
        return params;
    }

    @Override
    public Map<String, String> getImgParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("userId", user.getUserId()+"");
        params.put("op", "editHeadPic");
        params.put("tokenid", "6");
        Map<String, Object> signMap = new HashMap<>();
        signMap.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMap));
        return params;
    }
}
